from tools.initialization_config import *
import time
import hashlib
import json
from urllib import parse
from urllib.request import urlopen
from urllib import request as re


class YouDaoTranslateRecognizer(object):

    def __init__(self, lang_from='auto', lang_to='auto'):
        self.url = 'https://openapi.youdao.com/api/'
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36",
        }
        self.app_key, self.app_secret = self.get_youdao_api_config()
        self.lang_from = lang_from
        self.lang_to = lang_to

    def get_url_encoded_data(self, query_text):
        '''
        将数据url编码
            :param query_text: 待翻译的文字
            :return: 返回url编码过的数据
        '''
        # 产生随机数 ,其实固定值也可以,不如"2"
        salt = str(int(round(time.time() * 1000)))
        sign_str = self.app_key + query_text + salt + self.app_secret
        sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
        pay_load = {
            'q': query_text,
            'from': self.lang_from,
            'to': self.lang_to,
            'appKey': self.app_key,
            'salt': salt,
            'sign': sign
        }

        # 注意是get请求，不是请求
        data = parse.urlencode(pay_load)
        return data

    def parse_html(self, html):
        '''
        解析页面，输出翻译结果
            :param html: 翻译返回的页面内容
            :return: None
        '''
        data = json.loads(html)
        translation_result = data['translation']
        if isinstance(translation_result, list):
            translation_result = translation_result[0]

        return translation_result

    def get_youdao_api_config(self):
        _CONF_PATH = 'translate/youdao/YouDaoOAuth.ini'
        ini_parser = InitializationConfigParser(_CONF_PATH)
        client_credentials = ini_parser.GetAllNodeItems("ClientCredentials")
        app_key = client_credentials.get("app_key")
        app_secret = client_credentials.get("app_secret")
        return app_key, app_secret

    def translate(self, query_text):
        # 获取url编码过的数据
        data = self.get_url_encoded_data(query_text)
        # 构造目标url
        target_url = self.url + '?' + data
        # 构造请求
        request = re.Request(target_url, headers=self.headers)
        # 发送请求
        response = urlopen(request)
        # 解析，显示翻译结果
        return self.parse_html(response.read())
